﻿using IntelligentStorWpfApp.Model;
using log4net;
using System.Collections.Generic;
using System.Windows;
using IntelligentStorWpfApp.Controller;
using System.Windows.Threading;
using System.Windows.Input;
using System;
using System.Windows.Media.Imaging;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using WPFMediaKit.DirectShow.Controls;

namespace IntelligentStorWpfApp.View
{
    /// <summary>
    /// Login.xaml 的交互逻辑
    /// </summary>
    public partial class Login : Window
    {
        DispatcherTimer timer = new DispatcherTimer();
        private static readonly ILog log = LogManager.GetLogger(typeof(CabinetWindow));
        private UserController uscontroller = new UserController();
        public Login()
        {
            InitializeComponent();
            WindowStartupLocation = WindowStartupLocation.CenterScreen;
            //this.Topmost = true;
            //timer.Interval = TimeSpan.FromSeconds(1);
            //timer.Tick += Timer_Tick;
        }
        private void Login_Loaded(object sender, RoutedEventArgs e)
        {
            Storyboard sbd = Resources["leafLeave"] as Storyboard;
            sbd.Begin();

            Storyboard baiyun = Resources["cloudMove"] as Storyboard;
            baiyun.Begin();
        }
        /*
        private void Timer_Tick(object sender, EventArgs e)
        {
            //开个新线程
            Task.Factory.StartNew(() =>
            {
                //同步前端线程
                Dispatcher.Invoke(() =>
                {
                    //根据前端视频流控件的长宽高获取最佳的bitmap对象
                    RenderTargetBitmap bmp = new RenderTargetBitmap(
                   (int)vce.ActualWidth,
                   (int)vce.ActualHeight,
                   96, 96, PixelFormats.Default);
                    //渲染bitmap
                    bmp.Render(vce);
                    BitmapEncoder encoder = new JpegBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(bmp));
                    using (MemoryStream ms = new MemoryStream())
                    {
                        encoder.Save(ms);
                        byte[] captureData = ms.ToArray();
                        TaskAwaiter<JObject> awaiter = TFaceDetect(captureData).GetAwaiter();
                        awaiter.OnCompleted(() =>
                        {
                            //创建同步UI线程
                            Dispatcher.Invoke(() =>
                            {
                                JObject result = awaiter.GetResult();
                                //开始串结果文本
                                string content = "人脸数量: " + result["result_num"] + "\r\n";
                                if (result["result_num"].ToString() != "0")
                                {
                                    JToken Rresult = result["result"][0];
                                    content += "人脸置信度: " + Rresult["face_probability"] + "\r\n";
                                    int left = (int)Rresult["location"]["left"];
                                    int top = (int)Rresult["location"]["top"];
                                    int width = (int)Rresult["location"]["width"];
                                    int height = (int)Rresult["location"]["height"];
                                    string cusgender = Rresult["gender"].ToString() == "male" ? "男" : "女";
                                    content += "性别: " + cusgender + "\r\n";
                                    content += "年龄: " + (int)Rresult["age"] + "\r\n";
                                    content += "颜值: " + (int)Rresult["beauty"] + "\r\n";
                                    if (left > 0 && top > 0 && width > 0 && height > 0)
                                        CreateDrawingVisualRectangle(new Rect(left, top, width, height));
                                }
                            });
                        });

                        TaskAwaiter<JObject> awaiterIdentify = TFaceIdentify(captureData).GetAwaiter();
                        awaiterIdentify.OnCompleted(() =>
                        {

                            Dispatcher.Invoke(new Action(() =>
                            {
                                JObject result = awaiterIdentify.GetResult();
                                if (result["error_code"] != null)
                                    txt2.Text = "未识别有效人脸";
                                else
                                {
                                    uint num = (uint)result["result_num"];
                                    JToken Rresult = result["result"][0];
                                    string group_id = (string)Rresult["group_id"];
                                    string uid = (string)Rresult["uid"];
                                    string user_info = (string)Rresult["user_info"];
                                    string scores = Rresult["scores"][0].ToString();
                                    txt2.Text = num + "," + uid + "\r\n" + scores;
                                }
                            }));
                        });
                        
                    }
                });
            });
        }*/
       

        private void m_bt_login_Click(object sender, RoutedEventArgs e)
        {
            string userId = m_txt_user.Text.Trim();
            string pwd = m_pbox_password.Password;
            if(string.IsNullOrEmpty(userId))
            {
                nameValidate.Content = "请输入用户名！";
                nameValidate.Foreground = System.Windows.Media.Brushes.Red;
                return;
            }
            nameValidate.Content = "";
            if (string.IsNullOrEmpty(pwd))
            {

                pwdValidate.Content = "请输入密码！";
                pwdValidate.Foreground = System.Windows.Media.Brushes.Red;
                return;
            }
            pwdValidate.Content = "";

            List<User> userlist = new List<User>();
            User currentUser = new User();
            currentUser.UserName = userId;
            currentUser.UserPwd = pwd;
            userlist = uscontroller.GetUser(currentUser);
            if(userlist.Count>0)
            {
                currentUser.FaceId = userlist[0].FaceId;
                DefaultWindow defaultWin = new DefaultWindow();
                App.user = currentUser;
                this.Close();
                defaultWin.Show();
                
            }
            else
            {
                pwdValidate.Content = "用户名或密码错误！";
                pwdValidate.Foreground = System.Windows.Media.Brushes.Red;
                return;
            }
        }

        /*
        private Bitmap GetFaceBitmap(string path)
        {
            //string path ="";
            Bitmap bitmap = new Bitmap(path);
            Bitmap result = AForge.Imaging.Image.Clone(bitmap);
            bitmap.Dispose();
            return result;
        }

        public Bitmap GetCurrentFrame()
        {
            if (captureToken.Token.IsCancellationRequested) return null;
            lock (sync)
            {
                return (currentFrame == null || currentFrame.Width == 0 || currentFrame.Height == 0) ? null : AForge.Imaging.Image.Clone(currentFrame);
            }
        }


        /// <summary>
        /// 启动相机采集人脸
        /// </summary>
        private void startCappture()
        {
            FilterInfoCollection filters = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            videoCaptureDevice = new VideoCaptureDevice(filters[0].MonikerString);
            videoCaptureDevice.NewFrame += VideoCaptureDevice_NewFrame;
            videoCaptureDevice.Start();
            log.Info("usb相机采集开始");
            arcFaceApi = new ArcFaceApi();
            new Task(ValidFace, captureToken.Token).Start();
            

        }
        private void VideoCaptureDevice_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
        {
            Bitmap newFrame = (Bitmap)eventArgs.Frame.Clone();
            //如果使用视频文件请注释下面的这行代码，表示不对图像进行水平翻转
            newFrame.RotateFlip(RotateFlipType.Rotate180FlipY);
            System.Drawing.Image imgforms = (Bitmap)eventArgs.Frame.Clone();
            lock (sync)
            {
                if (currentFrame != null)
                {
                    currentFrame.Dispose();
                    currentFrame = null;
                }
                currentFrame = newFrame;
                //skinPictureBox2
                BitmapImage bi = new BitmapImage();
                bi.BeginInit();
                MemoryStream ms = new MemoryStream();
                imgforms.Save(ms, ImageFormat.Bmp);
                ms.Seek(0, SeekOrigin.Begin);
                bi.StreamSource = ms;
                bi.EndInit();
                bi.Freeze();

                Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    skinPictureBox2.Source = bi;
                }
                ));
            }
        }
        /// <summary>
        ///验证人脸 
        /// </summary>
        private void ValidFace()
        {
            Task.Delay(1000);
            Stopwatch stopwatch = Stopwatch.StartNew();
            Bitmap snapshotImage = null;
            while (!captureToken.IsCancellationRequested)
            {
                if (snapshotImage != null)
                {
                    snapshotImage.Dispose();
                    snapshotImage = null;
                }
                snapshotImage = GetCurrentFrame();
                if (snapshotImage == null)
                {
                    Task.Delay(1000);
                    continue;
                }
                bool result = arcFaceApi.MatchOneToOne(snapshotImage);
                log.DebugFormat("人脸查找结果 {0}", result);
                if (result)
                {
                    //查找物料存储信息
                }
                else
                {

                }
            
            }
            
        }
        */

        private void m_btIdentify_Click(object sender, RoutedEventArgs e)
        {
            if (MultimediaUtil.VideoInputNames.Length <= 0)
            {
                MessageBox.Show("电脑没有安装任何摄像头", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            FaceIdentify winFaceIdentify = new FaceIdentify();
            winFaceIdentify.Show();
            this.Close();
        }
        private void Login_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                DragMove();
            }
        }

        private void Image_MouseEnter(object sender, MouseEventArgs e)
        {
            Image ig = sender as Image;
            if (ig.Tag.ToString() == "close")
            {
                Uri ur = new Uri(@"/Image/close1.png", UriKind.Relative);
                BitmapImage bp = new BitmapImage(ur);
                ig.Source = bp;
            }
            else
            {
                Uri ur = new Uri(@"/Image/mini1.png", UriKind.Relative);
                BitmapImage bp = new BitmapImage(ur);
                ig.Source = bp;
            }
        }

        private void Image_MouseLeave(object sender, MouseEventArgs e)
        {
            Image ig = sender as Image;
            if (ig.Tag.ToString() == "close")
            {
                Uri ur = new Uri(@"/Image/close0.png", UriKind.Relative);
                BitmapImage bp = new BitmapImage(ur);
                ig.Source = bp;
            }
            else
            {
                Uri ur = new Uri("/Image/mini0.png", UriKind.Relative);
                BitmapImage bp = new BitmapImage(ur);
                ig.Source = bp;
            }
        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Image ig = sender as Image;
            if (ig.Tag.ToString() == "close")
            {
                this.Close();
            }
            else this.WindowState = WindowState.Minimized; ;
        }
    }
}
